//
//  AppDelegate.swift
//  WWDCLearn
//
//  Created by dev on 2021/6/28.
//

import Cocoa
import os.log
import Sparkle

extension Notification.Name {
    static let openWWDCURL = Notification.Name(rawValue: "OpenWWDCURLNotification")
}


@main
class AppDelegate: NSObject, NSApplicationDelegate {

   private lazy var agentController = WWDCAgentController()

    private let log = OSLog(subsystem: "io.wwdc.app", category: String(describing: AppDelegate.self))

    private lazy var commandsReceiver = AppCommandsReceiver()

    private(set) var coordinator:AppCoordinator? {
        didSet {
            if coordinator != nil {
              openPendingDeepLinkIfNeeded()
            }
        }
    }
    
    private var pendingDeepLink: DeepLink?

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }
    
    private func openPendingDeepLinkIfNeeded(){
        guard let deepLink = pendingDeepLink else { return  }

    }

    var startedAsAgent = false

    func applicationWillFinishLaunching(_ notification: Notification) {
        NSAppleEventManager.shared().setEventHandler(self, andSelector: #selector(handleURLEvent(_:replyEvent:)), forEventClass: UInt32(kInternetEventClass), andEventID: UInt32(kAEGetURL))

        if ProcessInfo.processInfo.arguments.contains("--background") {
            NSApp.setActivationPolicy(.accessory)
            startedAsAgent = true
            os_log("WWDC running in background mode to respond to deep-linked commands", log: self.log, type: .default)
        } else {
            NSApp.setActivationPolicy(.regular)
        }

        NSApplication.shared.appearance = NSAppearance(named: .darkAqua)

        #if ICLOUD
        ConfCoreCapabilities.isCloudKitEnabled = true
        #endif
    }


    @objc func handleURLEvent(_ event:NSAppleEventDescriptor?, replyEvent: NSAppleEventDescriptor?){
        guard let event = event else { return  }
        guard let urlString = event.paramDescriptor(forKeyword: UInt32(keyDirectObject))?.stringValue else { return  }
        guard let url = URL(string: urlString) else { return  }
         openURL(url)
    }
    private func openURL(_ url:URL){
        if let command = WWDCAppCommand(from: url) {

        }

    }
    private func activateUI(){


    }

}



extension AppDelegate :SUUpdaterDelegate {
    func updaterMayCheck(forUpdates updater: SUUpdater) -> Bool {
        #if DEBUG
        return ProcessInfo.processInfo.arguments.contains("--enable-update")
        #else
        return true
        #endif
    }
}

extension AppDelegate {
    func handle(_ command:WWDCAppCommand)  {
        if command.isForeground {
             activateUI()
            DispatchQueue.main.async {
                NSApp.activate(ignoringOtherApps: true)
            }
        }
    }
}
